package hos.permission.dialog;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.PermissionInfo;
import android.content.res.Configuration;
import android.graphics.PorterDuff;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

import hos.permission.PermissionConstants;
import hos.permission.R;

/**
 * <p>Title: DefaultDialog </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @version : 1.0
 * @date : 2024-01-08 13:39
 */
public class DefaultDialog extends RationaleDialog {

    @NonNull
    private final List<String> permissions;
    @NonNull
    private final String message;
    @NonNull
    private final String positiveText;
    @Nullable
    private final String negativeText;
    private int lightColor = -1;
    private int darkColor = -1;
    private TextView mMessageText;
    private LinearLayout mPermissionsLayout;
    @Nullable
    private LinearLayout mPositiveLayout;
    private Button mPositiveBtn;
    private LinearLayout mNegativeLayout;
    private Button mNegativeBtn;


    public DefaultDialog(@NonNull Context context,@NonNull List<String> permissions,
                         @NonNull String message) {
        this(context, permissions, message, "允许", "拒绝", -1, -1);
    }

    public DefaultDialog(@NonNull Context context,@NonNull List<String> permissions,
                         @NonNull String message,@NonNull String positiveText) {
        this(context, permissions, message, positiveText, null, -1, -1);
    }

    public DefaultDialog(@NonNull Context context,@NonNull List<String> permissions,
                         @NonNull String message,@NonNull String positiveText, String negativeText) {
        this(context, permissions, message, positiveText, negativeText, -1, -1);
    }

    public DefaultDialog(@NonNull Context context,@NonNull List<String> permissions,
                         @NonNull String message,@NonNull String positiveText,@Nullable String negativeText,
                         int lightColor, int darkColor) {
        super(context, R.style.PermissionDefaultDialog);
        this.permissions = permissions;
        this.message = message;
        this.positiveText = positiveText;
        this.negativeText = negativeText;
        this.lightColor = lightColor;
        this.darkColor = darkColor;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.permissionx_default_dialog_layout);
        initView();
        setupText();
        buildPermissionsLayout();
        setupWindow();
    }

    private void setupWindow() {
        Window window = getWindow();
        if (window == null) {
            return;
        }
        int width = getContext().getResources().getDisplayMetrics().widthPixels;
        int height = getContext().getResources().getDisplayMetrics().heightPixels;
        WindowManager.LayoutParams param = window.getAttributes();
        window.setGravity(Gravity.CENTER);
        if (width < height) {
            // now we are in portrait
            param.width = (int) (width * 0.86);
        } else {
            // now we are in landscape
            param.width = (int) (width * 0.6);
        }
        window.setAttributes(param);
    }

    private void buildPermissionsLayout() {
        HashSet<String> tempSet = new HashSet<String>();
        int currentVersion = Build.VERSION.SDK_INT;

        List<String> allSpecialPermissions = Arrays.asList(PermissionConstants.allSpecialPermissions);
        String permissionGroup = null;
        for (String permission : permissions) {
            if (currentVersion < Build.VERSION_CODES.Q) {
                try {
                    PermissionInfo permissionInfo = getContext().getPackageManager().getPermissionInfo(permission, 0);
                    permissionGroup = permissionInfo.group;
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            } else if (currentVersion == Build.VERSION_CODES.Q) {
                permissionGroup = PermissionConstants.permissionMapOnQ().get(permission);
            } else if (currentVersion == Build.VERSION_CODES.R) {
                permissionGroup = PermissionConstants.permissionMapOnR().get(permission);
            } else if (currentVersion == Build.VERSION_CODES.S) {
                permissionGroup = PermissionConstants.permissionMapOnS().get(permission);
            } else if (currentVersion == Build.VERSION_CODES.TIRAMISU) {
                permissionGroup = PermissionConstants.permissionMapOnT().get(permission);
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    permissionGroup = PermissionConstants.permissionMapOnT().get(permission);
                }
            }
            if ((allSpecialPermissions.contains(permission) && !tempSet.contains(permission))
                    || (permissionGroup != null && !tempSet.contains(permissionGroup))) {
                ViewGroup itemLayout = (ViewGroup) View.inflate(getContext(), R.layout.permissionx_permission_item, null);
                TextView permissionText = itemLayout.findViewById(R.id.permissionText);
                ImageView permissionIcon = itemLayout.findViewById(R.id.permissionIcon);
                int icon = 0;
                int labelRes = 0;
                if (permissionGroup != null && !permissionGroup.isEmpty()) {
                    try {
                        icon = getContext().getPackageManager().getPermissionGroupInfo(permissionGroup
                                , 0).icon;
                        labelRes = getContext().getPackageManager().getPermissionGroupInfo(permissionGroup
                                , 0).labelRes;
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                if (permission.equals(Manifest.permission.ACCESS_BACKGROUND_LOCATION)) {
                    permissionText.setText(getContext().getString(R.string.permissionx_access_background_location));
                    permissionIcon.setImageResource(icon);
                } else if (permission.equals(Manifest.permission.MANAGE_EXTERNAL_STORAGE)) {
                    permissionText.setText(getContext().getString(R.string.permissionx_manage_external_storage));
                    permissionIcon.setImageResource(icon);
                } else if (permission.equals(Manifest.permission.SYSTEM_ALERT_WINDOW)) {
                    permissionText.setText(getContext().getString(R.string.permissionx_system_alert_window));
                    permissionIcon.setImageResource(R.drawable.permissionx_ic_alert);
                } else if (permission.equals(Manifest.permission.WRITE_SETTINGS)) {
                    permissionText.setText(getContext().getString(R.string.permissionx_write_settings));
                    permissionIcon.setImageResource(R.drawable.permissionx_ic_setting);
                } else if (permission.equals(Manifest.permission.REQUEST_INSTALL_PACKAGES)) {
                    permissionText.setText(getContext().getString(R.string.permissionx_request_install_packages));
                    permissionIcon.setImageResource(R.drawable.permissionx_ic_install);
                } else if (permission.equals(Manifest.permission.POST_NOTIFICATIONS)
                        && Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
                    permissionText.setText(getContext().getString(R.string.permissionx_post_notification));
                    permissionIcon.setImageResource(R.drawable.permissionx_ic_notification);
                } else if (permission.equals(Manifest.permission.BODY_SENSORS_BACKGROUND)) {
                    permissionText.setText(getContext().getString(R.string.permissionx_body_sensor_background));
                    permissionIcon.setImageResource(icon);
                } else {
                    permissionText.setText(getContext().getString(labelRes));
                    permissionIcon.setImageResource(icon);
                }
                if (isDarkTheme()) {
                    if (darkColor != -1) {
                        permissionIcon.setColorFilter(darkColor, PorterDuff.Mode.SRC_ATOP);
                    }
                } else {
                    if (lightColor != -1) {
                        permissionIcon.setColorFilter(lightColor, PorterDuff.Mode.SRC_ATOP);
                    }
                }
                mPermissionsLayout.addView(itemLayout);
                if (permissionGroup != null && !permissionGroup.isEmpty()) {
                    tempSet.add(permissionGroup);
                } else {
                    tempSet.add(permission);
                }
            }
        }
    }

    private void setupText() {
        mMessageText.setText(message);
        mPositiveBtn.setText(positiveText);
        if (negativeText != null && !negativeText.isEmpty()) {
            mNegativeLayout.setVisibility(View.VISIBLE);
            mNegativeBtn.setText(negativeText);
        } else {
            mNegativeLayout.setVisibility(View.GONE);
        }
        if (isDarkTheme()) {
            if (darkColor != -1) {
                mPositiveBtn.setTextColor(darkColor);
                mNegativeBtn.setTextColor(darkColor);
            }
        } else {
            if (lightColor != -1) {
                mPositiveBtn.setTextColor(lightColor);
                mNegativeBtn.setTextColor(lightColor);
            }
        }
    }

    @NonNull
    @Override
    public View getPositiveButton() {
        return mPositiveBtn;
    }

    @Nullable
    @Override
    public View getNegativeButton() {
        if (negativeText == null || negativeText.length() == 0) {
            return null;
        }
        return mNegativeBtn;
    }

    @NonNull
    @Override
    public List<String> getPermissionsToRequest() {
        return permissions;
    }

    public boolean isPermissionLayoutEmpty() {
        return mPermissionsLayout.getChildCount() == 0;
    }

    private void initView() {
        mMessageText = (TextView) findViewById(R.id.messageText);
        mPermissionsLayout = (LinearLayout) findViewById(R.id.permissionsLayout);
        mPositiveLayout = (LinearLayout) findViewById(R.id.positiveLayout);
        mPositiveBtn = (Button) findViewById(R.id.positiveBtn);
        mNegativeLayout = (LinearLayout) findViewById(R.id.negativeLayout);
        mNegativeBtn = (Button) findViewById(R.id.negativeBtn);
    }

    /**
     * Currently we are in dark theme or not.
     */
    private boolean isDarkTheme() {
        int flag = getContext().getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
        return flag == Configuration.UI_MODE_NIGHT_YES;
    }
}
